﻿/**
* jQuery.sp  - extend jQuery，by tony
**/
var objValueArray = new Array(); //输入框提示缓存数据

jQuery.extend(
{
    sp: {
        //格式化字符串，与.net类似，exp:jQuery.sp.format("{0}+{1}",0,1)
        format: function() {
            if (arguments.length == 0) return null;
            var str = arguments[0];
            for (var i = 1; i < arguments.length; i++) {
                var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
                str = str.replace(re, arguments[i]);
            }
            return str;
        },
        //输入框提示，exp:onclick = jQuery.sp.changeInputValue(this)
        changeInputValue: function(obj) {
            jQuery(obj).bind("blur", function() {
                if (jQuery(this).val() == "" && typeof (objValueArray[jQuery(this).attr("name")]) != "undefined") { jQuery(this).val(objValueArray[jQuery(this).attr("name")]); }
            });
            if (typeof (objValueArray[jQuery(obj).attr("name")]) == "undefined" || jQuery(obj).val() == objValueArray[jQuery(obj).attr("name")]) {
                objValueArray[jQuery(obj).attr("name")] = jQuery(obj).val();
                jQuery(obj).val("");
            }
        },
        //按比例缩放图片，exp:onload = jQuery.sp.picsize(this,50,40)
        picsize: function(obj, MaxWidth, MaxHeight) {
            img = new Image();
            img.src = obj.src;
            if (img.width > MaxWidth && img.height > MaxHeight) {
                if (img.width / img.height > MaxWidth / MaxHeight) {
                    obj.height = MaxWidth * img.height / img.width;
                    obj.width = MaxWidth;
                }
                else {
                    obj.width = MaxHeight * img.width / img.height;
                    obj.height = MaxHeight;
                }
            }
            else if (img.width > MaxWidth) {
                obj.height = MaxWidth * img.height / img.width;
                obj.width = MaxWidth;
            }
            else if (img.height > MaxHeight) {
                obj.width = MaxHeight * img.width / img.height;
                obj.height = MaxHeight;
            }
            else {
                obj.width = img.width;
                obj.height = img.height;
            }
        },
        //cookie write
        setCookie: function(name, value, minutes) {
            if (arguments.length < 3)
                minutes = 1;
            var expTime = new Date();
            expTime.setTime(expTime.getTime() + minutes * 60 * 1000);
            document.cookie = name + "=" + encodeURI(value) + ";expires=" + expTime.toGMTString() + ";path=/";
        },
        //cookie read
        getCookie: function(name) {
            var arrCookies = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
            if (arrCookies != null) return decodeURI(arrCookies[2]); return null;
        },
        //找到所有的标签页，并实现可切换，exp:jQuery.sp.findAllTab("Tab"),jQuery.sp.findAllTab("Tab","li")
        //推荐使用jquery.tools
        findAllTab: function(tabClassName) {
            var allTab = jQuery("." + tabClassName);
            for (var i = 0; i < allTab.length; i++) {
                var thisTab = jQuery(allTab[i]);
                var isOnClick = thisTab.attr("class").indexOf("click") > 0;
                var thisTabChildren = thisTab.children(arguments.length > 1 ? arguments[1] : "a");
                var thisTabContent = jQuery("#" + thisTab.attr("id") + "_content");
                var thisTabContentChildren = thisTabContent.children(".tabcontent");

                for (var j = 0; j < thisTabChildren.length; j++) {
                    var tab = jQuery(thisTabChildren[j]);
                    var content = jQuery(thisTabContentChildren[j]);
                    tab.attr("id", thisTab.attr("id") + "_" + j);
                    content.attr("id", thisTab.attr("id") + "_content_" + j);
                    if (isOnClick) {
                        tab.click(function() {
                            var tempArr = jQuery(this).attr("id").split("_");
                            for (var k = 0; k < jQuery(this).parent().children().length; k++) {
                                jQuery("#" + tempArr[0] + "_" + k).removeClass("select");
                                jQuery("#" + tempArr[0] + "_content_" + k).addClass("nodisplay");
                            }
                            jQuery("#" + tempArr[0] + "_" + tempArr[1]).addClass("select");
                            jQuery("#" + tempArr[0] + "_content_" + tempArr[1]).removeClass("nodisplay");
                        });
                    }
                    else {
                        tab.mouseover(function() {
                            var tempArr = jQuery(this).attr("id").split("_");
                            for (var k = 0; k < jQuery(this).parent().children().length; k++) {
                                jQuery("#" + tempArr[0] + "_" + k).removeClass("select");
                                jQuery("#" + tempArr[0] + "_content_" + k).addClass("nodisplay");
                            }
                            jQuery("#" + tempArr[0] + "_" + tempArr[1]).addClass("select");
                            jQuery("#" + tempArr[0] + "_content_" + tempArr[1]).removeClass("nodisplay");
                        });
                    }

                }
            }
        },
        //Call WebService, return Json
        //exp:jQuery.sp.WebServiceJsonCall("/WebService.asmx/WSFun", function(json) { jsFun(json); }, "{key:'value'}")
        WebServiceJsonCall: function(url, callback, pars) {
            jQuery.ajax({
                data: pars,
                url: url,
                type: "post",
                contentType: "application/json;utf-8",
                dataType: 'json',
                cache: false,
                success: function(json) {
                    callback(json.d);
                },
                error: function(xml, status) {
                    if (status == 'error') {
                        try {
                            var json = eval('(' + xml.responseText + ')');
                            alert(json.Message + '\n' + json.StackTrace);
                        } catch (e) { }
                    } else {
                        alert(status);
                    }
                },
                beforeSend: function(xml) {
                    if (!pars) xml.setRequestHeader("Content-Type", "application/json;utf-8")
                }
            });
        },
        //解析.NET WS返回的/Date(127xxxxx)/的日期格式为JavaScript日期格式，exp:jQuery.sp.deJsonDate(this.date)
        deJsonDate: function(dateStr) {
            try {
                var exp = dateStr.replace(new RegExp('/Date\\((-?[0-9]+)\\)/', 'g'), "new Date($1)"); //
                return eval('(' + exp + ')');
            }
            catch (e) {
                return new Date();
            }
        },
        //对象允许拖动，exp:jQuery.sp.dragObj("#objTitle","#obj",false);
        dragObj: function(c) {
            var obj = c;
            var isGetParent = false;
            if (arguments.length >= 2) { obj = arguments[1]; }
            if (arguments.length >= 3) { isGetParent = arguments[2]; }
            jQuery(c).css("cursor", "move");
            obj = isGetParent ? jQuery(obj).parent() : jQuery(obj);
            obj.css("position", "absolute");

            jQuery(c).mousedown(function(event) {
                var offset = jQuery(c).offset();
                var x1 = event.clientX - offset.left;
                var y1 = event.clientY - offset.top;
                var switchButton = false;
                if (document.all && event.button == 1) {
                    switchButton = true;
                }
                else {
                    if (event.button == 0)
                        switchButton = true;
                }
                if (switchButton)//按左键,FF是0，IE是1
                {
                    jQuery(document).mousemove(function(event) {

                        obj.css("left", (event.clientX - x1) + "px");
                        obj.css("top", (event.clientY - y1) + "px");
                        return false;
                    });
                }
            })
            jQuery(c).mouseup(function(event) {
                jQuery(document).unbind("mousemove");
            })
        },
        //展示分页，exp:jQuery.sp.showPaging("pager",1,20,999,"paging({0},{1})"); //{0}=pageIndex,{1}=pageSize
        showPaging: function(objID, pageIndex, pageSize, rowCount, pagingFormat) {
            var htmlContent = "";
            jQuery("#" + objID).html(htmlContent);
            if (rowCount > pageSize) {
                //compute
                var pageCount = parseInt(Math.ceil(parseFloat(rowCount) / parseFloat(pageSize)));
                var prePageIndex = pageIndex > 1 ? parseInt(pageIndex) - 1 : parseInt(pageIndex);
                var nextPageIndex = pageIndex < pageCount ? parseInt(pageIndex) + 1 : parseInt(pageIndex);
                if (pageIndex == 1) {
                    htmlContent += "<a class=\"first\" href=\"#\">首&nbsp;页</a> &nbsp;&nbsp;";
                    htmlContent += "<a class=\"prev\" href=\"#\">上一页</a>&nbsp;&nbsp;";
                }
                else {
                    htmlContent += jQuery.sp.format("<a class=\"first\" href=\"javascript:{0};\" title=\"查看第1页\">首&nbsp;页</a> &nbsp;&nbsp;", jQuery.sp.format(pagingFormat, 1, pageSize));
                    htmlContent += jQuery.sp.format("<a class=\"prev\" href=\"javascript:{0};\" title=\"查看第{1}页\">上一页</a>&nbsp;&nbsp;", jQuery.sp.format(pagingFormat, prePageIndex, pageSize), prePageIndex);
                }
                if (pageIndex == pageCount) {
                    htmlContent += "<a href=\"#\">下一页</a>&nbsp;&nbsp;";
                    htmlContent += "<a href=\"#\">尾&nbsp;页</a>&nbsp;&nbsp;";
                }
                else {
                    htmlContent += jQuery.sp.format("<a href=\"javascript:{0};\" title=\"查看第{1}页\">下一页</a>&nbsp;&nbsp;", jQuery.sp.format(pagingFormat, nextPageIndex, pageSize), nextPageIndex);
                    htmlContent += jQuery.sp.format("<a href=\"javascript:{0};\" title=\"查看最后一页\">尾&nbsp;页</a>&nbsp;&nbsp;", jQuery.sp.format(pagingFormat, pageCount, pageSize));
                }
                htmlContent += jQuery.sp.format("共&nbsp;{0}/{1}&nbsp;页&nbsp;&nbsp;共&nbsp;{2}&nbsp;条 ", pageIndex, pageCount, rowCount);
                htmlContent += jQuery.sp.format("转到<select onchange=\"{0};\">", jQuery.sp.format(pagingFormat, "this.value", pageSize));
                for (var n = 1; n <= pageCount; n++) {
                    htmlContent += jQuery.sp.format("<option value=\"{0}\"{1}>{0}</option>", n, n == pageIndex ? " selected=\"selected\"" : "");
                }
                htmlContent += jQuery.sp.format("</select>页");
            }
            else {
                htmlContent += jQuery.sp.format("共有{0}条", rowCount);
            }
            jQuery("#" + objID).html(htmlContent);
        }
    }
});

//lazyload [http://www.appelsiini.net/projects/lazyload] 
//exp:$("img").lazyload({placeholder:"/Js/Img/fill.gif",effect:"fadeIn"});
(function ($) {
    $.fn.lazyload = function (options) {
        var settings = { threshold: 0, failurelimit: 0, event: "scroll", effect: "show", container: window }; if (options) { $.extend(settings, options); }
        var elements = this; if ("scroll" == settings.event) { $(settings.container).bind("scroll", function (event) { var counter = 0; elements.each(function () { if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) { } else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) { $(this).trigger("appear"); } else { if (counter++ > settings.failurelimit) { return false; } } }); var temp = $.grep(elements, function (element) { return !element.loaded; }); elements = $(temp); }); }
        this.each(function () {
            var self = this; if (undefined == $(self).attr("original")) { $(self).attr("original", $(self).attr("src")); }
            if ("scroll" != settings.event || undefined == $(self).attr("src") || settings.placeholder == $(self).attr("src") || ($.abovethetop(self, settings) || $.leftofbegin(self, settings) || $.belowthefold(self, settings) || $.rightoffold(self, settings))) {
                if (settings.placeholder) { $(self).attr("src", settings.placeholder); } else { $(self).removeAttr("src"); }
                self.loaded = false;
            } else { self.loaded = true; }
            $(self).one("appear", function () {
                if (!this.loaded) {
                    $("<img />").bind("load", function () {
                        $(self).hide().attr("src", $(self).attr("original"))
[settings.effect](settings.effectspeed); self.loaded = true;
                    }).attr("src", $(self).attr("original"));
                };
            }); if ("scroll" != settings.event) { $(self).bind(settings.event, function (event) { if (!self.loaded) { $(self).trigger("appear"); } }); } 
        }); $(settings.container).trigger(settings.event); return this;
    }; $.belowthefold = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).height() + $(window).scrollTop(); } else { var fold = $(settings.container).offset().top + $(settings.container).height(); }
        return fold <= $(element).offset().top - settings.threshold;
    }; $.rightoffold = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).width() + $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left + $(settings.container).width(); }
        return fold <= $(element).offset().left - settings.threshold;
    }; $.abovethetop = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollTop(); } else { var fold = $(settings.container).offset().top; }
        return fold >= $(element).offset().top + settings.threshold + $(element).height();
    }; $.leftofbegin = function (element, settings) {
        if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left; }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    }; $.extend($.expr[':'], { "below-the-fold": "$.belowthefold(a, {threshold : 0, container: window})", "above-the-fold": "!$.belowthefold(a, {threshold : 0, container: window})", "right-of-fold": "$.rightoffold(a, {threshold : 0, container: window})", "left-of-fold": "!$.rightoffold(a, {threshold : 0, container: window})" });
})(jQuery);